import React, { Component } from 'react'
// import axios from 'axios'
import request from '../util/request'

export default class Login extends Component {
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                用户名: <input type="text" name="username" value={username} onChange={this.change}></input><br></br>
                密码:<input type="text" name="password" value={password} onChange={this.change}></input>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }

    change = (e) => {
        console.log(e.target.value);
        console.log(e.target.name);
        this.setState({
            [e.target.name]:e.target.value
        })
    }

    login = () => {
        let {username,password} = this.state;
        if(username && password){
            request.post('/api/login',{username,password}).then(res => {
                if(res.code === 1){
                    console.log("登录成功");
                    localStorage.setItem('username',this.state.username);
                    localStorage.setItem('role_name',res.role_name);
                    localStorage.setItem('role_id',res.role_id);
                    localStorage.setItem('token',res.token);
                    //存完之后，再跳页面
                    this.props.history.push('/main');
                }else{
                    console.log("登录失败")
                }
            })
        }else{
            console.log("参数不完整")
        }
    }
}
